/*
	Copyright (c) 2004 Cory Nelson

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gamestat.h"
#include "internal.h"

typedef struct {
	char check[4];
	char data[1];
} ASE_PACKET;

static char *ase_parsestring(char **data) {
	unsigned char len=((unsigned char*)(*data))[0]; (*data)++;

	if(len>1) {
		char *str=malloc(len);

		len--;

		memcpy(str, *data, len);
		str[len]='\0';

		(*data)+=len;

		return str;
	}
	else return NULL;
}

static int ase_parseint(char **data) {
	char *intstr=ase_parsestring(data);
	if(intstr) {
		int i=atoi(intstr);
		free(intstr);
		return i;
	}
	else return 0;
}

int ase_skipstring(char **data) {
	unsigned char len=((unsigned char*)(*data))[0];
	(*data)+=len;

	return len;
}

GS_SERVERINFO *queryserver_ase(const char *host, unsigned short port) {
	SOCKET s=getsockudp(host, port);
	size_t packetlen;
	ASE_PACKET *packet;
	GS_SERVERINFO *info;
	GS_PROPERTY *curproperty=NULL;
	GS_PLAYERINFO *curplayer=NULL;
	char *iter, *end;
	clock_t ping;
	int i;
	
	if(s==INVALID_SOCKET) return NULL;

	ping=clock();
	if(send(s, "s", 1, 0)==SOCKET_ERROR) {
		lasterror=GS_ERROR_TIMEOUT;
		closesocket(s);
		return NULL;
	}
	packet=(ASE_PACKET*)getpacket(s, &packetlen);
	if(!packet) {
		lasterror=GS_ERROR_TIMEOUT;
		closesocket(s);
		return NULL;
	}
	ping=clock()-ping;
	closesocket(s);

	dbg_dumpbuf("ase.bin", packet, packetlen);

	if(memcmp(packet->check, "EYE1", 4)) {
		lasterror=GS_ERROR_CORRUPT;
		free(packet);
		return NULL;
	}

	info=calloc(1, sizeof(GS_SERVERINFO));
	info->ping=(int)ping;

	iter=packet->data;
	end=((char*)packet)+packetlen;

	if(iter>=end) goto err;
	ase_skipstring(&iter); // skip game code

	if(iter>=end) goto err;
	ase_skipstring(&iter); // skip port

	if(iter>=end) goto err;
	info->host=ase_parsestring(&iter);

	if(iter>=end) goto err;
	info->mod=ase_parsestring(&iter);

	if(iter>=end) goto err;
	info->map=ase_parsestring(&iter);

	if(iter>=end) goto err;
	ase_skipstring(&iter); // skip version

	if(iter>=end) goto err;
	ase_skipstring(&iter); // skip password

	if(iter>=end) goto err;
	info->numplayers=ase_parseint(&iter);

	if(iter>=end) goto err;
	info->maxplayers=ase_parseint(&iter);

	while(iter<end) {
		char *key=ase_parsestring(&iter);

		if(key) {
			if(iter<end) {
				GS_PROPERTY *property=malloc(sizeof(GS_PROPERTY));

				property->key=key;
				property->value=ase_parsestring(&iter);
				property->next=NULL;

				if(property->value) {
					if(!stricmp(property->key, "gr_TimeLimit")) info->timelimit=atoi(property->value);
					else if(!stricmp(property->key, "time")) info->timelimit=atoi(property->value)/60;
					else if(!stricmp(property->key, "gr_ScoreLimit")) info->scorelimit=atoi(property->value);
				}

				if(curproperty) curproperty=curproperty->next=property;
				else curproperty=info->properties=property;
			}
			else free(key);
		}
		else break;
	}

	for(i=0; iter<end && i<info->numplayers; i++) {
		GS_PLAYERINFO *player=calloc(1, sizeof(GS_PLAYERINFO));
		unsigned char flags=((unsigned char*)(iter))[0]; (iter)++;

		if(iter<end && flags&1) player->name=ase_parsestring(&iter);
		if(iter<end && flags&2) ase_skipstring(&iter);	// team
		if(iter<end && flags&4) ase_skipstring(&iter);	// skin
		if(iter<end && flags&8) player->score=ase_parseint(&iter);
		if(iter<end && flags&16) player->ping=ase_parseint(&iter);
		if(iter<end && flags&32) {
			char *value=ase_parsestring(&iter);
			if(value) {
				char type;

				if(sscanf(value, "%d%c", &player->time, &type)==2) {
					switch(type) {
						case 'm':
							player->time*=60;
							break;
						case 'h':
							player->time=player->time*60*60;
							break;
					}
				}
				free(value);
			}
		}
		if(iter<end && flags&64) ase_skipstring(&iter);
		if(iter<end && flags&128) ase_skipstring(&iter);

		if(curplayer) curplayer=curplayer->next=player;
		else curplayer=info->players=player;
	}

	free(packet);

	lasterror=GS_OK;
	return info;

err:
	lasterror=GS_ERROR_CORRUPT;
	free(packet);
	GSFreeServerInfo(info);
	return NULL;
}
